package com.umeox.logger

import android.os.Environment
import android.os.Handler
import android.os.HandlerThread
import com.umeox.logger.UMLogger.canSave2File
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class Logger2FileInterceptor : AbsLogInterceptChain() {

    private var file: File? = null
    private val handlerThread = HandlerThread("logger_to_file_thread")

    init {
        handlerThread.start()
    }

    private fun init() {
        Handler(handlerThread.looper).post {
            Environment.getExternalStorageDirectory().let {
                file = File(it, "umlogs.txt")
                if (!file!!.exists()) {
                    try {
                        //在指定的文件夹中创建文件
                        file!!.createNewFile()
                    } catch (e: Exception) {
                        return@post
                    }
                }

                //删除无用文件 只存放三天的数据
                it.listFiles()?.let { files ->
                    for (file in files) {
                        try {
                            if (file.name == "umlogs.txt") {
                                file.delete()
                            }
                        } catch (e: Exception) {
                            UMLogger.e("Logger2FileInterceptor", "删除日志文件失败", e)
                        }
                    }
                }
            }
        }
    }

    override fun intercept(priority: Int, tag: String, logMsg: String?, throwable: Throwable?) {
        if (!canSave2File) {
            return
        }
        Handler(handlerThread.looper).post {
            if (file == null) {
                init()
                intercept(priority, tag, logMsg, throwable)
                return@post
            }

            val date = Date()
            val needWriteMessage: String =
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(date)
                    .toString() + "    " + tag + "    " + logMsg + "\n"
            try {
                file!!.appendText(needWriteMessage)
            } catch (e: Exception) {
                return@post
            }
        }
    }
}